package com.sumainfor.pc.market.service;

import com.sumainfor.common.Constants;
import com.sumainfor.common.entity.SysUserVo;
import com.sumainfor.common.util.ContextUtils;
import com.sumainfor.common.util.JsonResult;
import com.sumainfor.common.utlis.ComUtils;
import com.sumainfor.common.utlis.ParamsCommon;
import com.sumainfor.pc.market.dao.*;
import com.sumainfor.pc.market.feign.Zfeign.ZpcEpcFeign;
import com.sumainfor.pc.market.feign.Zfeign.ZzuulFeign;
import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 服务中心经理房源定价
 */
@Service
public class SeHousingInfoService implements Serializable {

    private ReentrantLock lock = new ReentrantLock(false);

    Logger log = LoggerFactory.getLogger(SeHousingInfoService.class);// 日志

    @Autowired
    private SeHousingInfoMapper seHousingInfoMapper;
    @Autowired
    private SeHousingConInfoMapper seHousingConInfoMapper;
    @Autowired
    private SeHousingConMapper seHousingConMapper;
    @Autowired
    private SeHousingInfoPricingMapper seHousingInfoPricingMapper;
    @Autowired
    private ZzuulFeign ZzuulFeign;
    @Autowired
    private UtilsMapper utilsMapper;
    @Autowired
    private ZpcEpcFeign zpcEpcFeign;
    @Autowired
    private RdEpcStyleMapper rdEpcStyleMapper;
    String UUID=null;
    /**
     *查询待定价的房源列表
     */
    public List<Map<String,Object>> getSeHousingInfoList(Map<String, Object> params){
        List<Map<String,Object>> list=seHousingInfoMapper.getSeHousingInfoList(params);
        List<String> idList=new ArrayList<String>();//保存收房专员的id
        for (Map<String,Object> map:list) {
            if (map.get("InclusionId")!=null){
                idList.add(map.get("InclusionId").toString());
            }
        }
        if(idList.size()>0){
            JsonResult result=ZzuulFeign.getButlerName(idList);
            List<Map<String,Object>> zuulList=(List<Map<String,Object>>)result.get("result");
            if (result.get("errorCode").equals("0")) {
                for (Map<String, Object> map : list) {
                    for (Map<String, Object> map2 : zuulList) {
                        if (MapUtils.getString(map, "InclusionId").equals(MapUtils.getString(map2, "user_id"))) {
                            map.putAll(map2);
                        }
                    }
                }
            }
        }

        return list;
    }
    /**
     * 查询待定价的房源列表总数
     */
    public Integer getSeHousingInfoListCount(Map<String, Object> params){
        return seHousingInfoMapper.getSeHousingInfoListCount(params);
    }
    /**
     * 查询定价详情房间配置列表
     */
    public JsonResult getSeHousingInfoListByHouId(Map<String,Object> params){
        JsonResult result=new JsonResult();
        if (params.get("HouId")==null){
            return result.putFailed("参数不正确");
        }
        List<Map<String,Object>> list=seHousingInfoMapper.getSeHousingInfoListByHouId(params);
        //查询房源特色
        List<Map<String,Object>> sryleList=rdEpcStyleMapper.getRdEpcStyleList();
        System.out.println("市场部:"+list);
        JsonResult zepcResult=zpcEpcFeign.getHoRdHpiList(params);
        System.out.println("工程部:"+zepcResult);
        if (zepcResult.get("errorCode").toString().equals("0")){
            List<Map<String,Object>> zepcList=(List<Map<String,Object>>)zepcResult.get("result");
            for (Map<String,Object> map1:list){
                if (map1.get("HouConId")!=null){
                    for (Map<String,Object> map2:zepcList){
                        if (map2.get("HouConId")!=null){
                            if (map1.get("HouConId").toString().equals(map2.get("HouConId").toString())){
                                map1.putAll(map2);
                            }
                        }
                    }
                }
            }
            //匹配房源特色
            for (Map<String,Object> map1:list){
                String StyleIdName="";
                if (map1.get("StyleId")!=null){
                    for (Map<String,Object> map2:sryleList){
                        if (map2.get("Id")!=null){
                            if (map1.get("StyleId").toString().contains(map2.get("Id").toString())){
                                StyleIdName+=map2.get("Name")+",";
                            }
                        }
                    }
                }
                map1.put("StyleIdName",StyleIdName);
            }
        }
        if (list!=null){
            result.put(list);
        }else{
            result.putFailed("服务器繁忙");
        }
        return result;

    }
    /**
     * 修改房源的统一定价
     */
    public Integer updateSeHousingInfo(Map<String,Object> params){
        Integer result=0;
        /**
         * 加锁操作
         */
        lock.lock();
        try{
            try {
                params.put("by", ContextUtils.getUserId());//操作人
                params.put("term", "2");// 更新端 Update端： 1 租客端 2市场部 3 工程部   4运营部   5财务部  6总经办 7发展部
                params.put("fnc",
                        this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                ParamsCommon.commonUpdateParms(params);
                System.out.println("params:"+params);
                List<Map<String,Object>> list=(List<Map<String,Object>>)params.get("data");
                System.out.println("list:"+list);
                List<Map<String,Object>> lister=(List<Map<String,Object>>)params.get("dataer");
                if(params.get("ProOperaType").toString().equals("1")){//房源租赁类型 1.合租 2.整租
                    Map<String,Object>uuid=utilsMapper.getUUID(new HashMap<String,Object>(){{
                        put("uuid", "HouPrId");
                        put("database", Constants.DATA_SOURCE_TCMKT);
                        put("surface", "tcmkt_housing_info_pricing");
                    }});
                    if(uuid!=null &&(!uuid.get("uuid").toString().equals(""))){
                        int number=Integer.valueOf(uuid.get("uuid").toString());
                        UUID= ComUtils.getLocalTrmSeqNum("hi",number);
                    }else{
                        UUID=ComUtils.getLocalTrmSeqNum("hi",0);
                    }
                    for (int i=0;i<list.size();i++){
                        Map<String,Object> map=(Map<String,Object>)list.get(i);
                        System.out.println("新增之前的参数:"+map);
                        if (params.get("PricingStatus")!=null) {
                            map.putAll(params);
                            map.put("PricingStatus", params.get("PricingStatus"));
                        }
                        map.put("Founder", ContextUtils.getUserId());//房源定价人编号
                        result=seHousingInfoMapper.updateSeHousingInfo(map);
                        if (params.get("ProOperaType").toString().equals("2") && map.get("HouConType").toString().equals("2")){
                        }else{
                            Map<String,Object> dataMap=new HashMap<String,Object>();
                            dataMap.put("HouPrId",UUID);
                            dataMap.put("by", ContextUtils.getUserId());//操作人
                            dataMap.put("term", "2");// 创建端 Insert端： 1 租客端 2市场部 3 工程部   4运营部   5财务部  6总经办 7发展部
                            dataMap.put("fnc",
                                    this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                            ParamsCommon.commonInsertParms(dataMap);
                            SysUserVo user=ContextUtils.getSysUser();
                            dataMap.put("HouId",params.get("HouId"));
                            dataMap.put("HouInfoId",map.get("HouInfoId"));
                            dataMap.put("IfNew",params.get("ifNew"));//是否新增或者修改      0新增   1修改   2审核

                            if(!dataMap.get("IfNew").toString().equals("0")){
                                dataMap.put("FPricing",lister.get(i).get("UnifiedPricing"));
                            }
                            dataMap.put("TPricing",map.get("UnifiedPricing"));//房源统一定价(变化后)
                            dataMap.put("OperId",dataMap.get("insby"));//当前操作人编号
                            dataMap.put("OperName",user.getName());//当前操作人名称
                            dataMap.put("OperTime",dataMap.get("instm"));//操作时间
                            seHousingInfoPricingMapper.addSeHousingInfoPricing(dataMap);
                        }
                    }
                }else{//盈利预测为整租的情况
                    Map<String,Object>uuid=utilsMapper.getUUID(new HashMap<String,Object>(){{
                        put("uuid", "HouPrId");
                        put("database", Constants.DATA_SOURCE_TCMKT);
                        put("surface", "tcmkt_housing_info_pricing");
                    }});
                    if(uuid!=null &&(!uuid.get("uuid").toString().equals(""))){
                        int number=Integer.valueOf(uuid.get("uuid").toString());
                        UUID= ComUtils.getLocalTrmSeqNum("hi",number);
                    }else{
                        UUID=ComUtils.getLocalTrmSeqNum("hi",0);
                    }
                    for (int i=0;i<list.size();i++){
                        Map<String,Object> map=(Map<String,Object>)list.get(i);
                        if (params.get("PricingStatus")!=null) {
                            map.putAll(params);
                            map.put("PricingStatus", params.get("PricingStatus"));
                        }
                        if (map.get("HouConType").toString().equals("1")) {
                            result=seHousingInfoMapper.updateSeHousingInfo(map);
                        }
                     /*   if (params.get("ProOperaType").toString().equals("2") && map.get("HouConType").toString().equals("2")){

                        }else{*/
                        Map<String,Object> dataMap=new HashMap<String,Object>();
                        dataMap.put("HouPrId",UUID);
                        dataMap.put("by", ContextUtils.getUserId());//操作人
                        dataMap.put("term", "2");// 创建端 Insert端： 1 租客端 2市场部 3 工程部   4运营部   5财务部  6总经办 7发展部
                        dataMap.put("fnc",
                                this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                        ParamsCommon.commonInsertParms(dataMap);
                        SysUserVo user=ContextUtils.getSysUser();
                        dataMap.put("HouId",params.get("HouId"));
                        dataMap.put("HouInfoId",map.get("HouInfoId"));
                        dataMap.put("IfNew",params.get("ifNew"));//是否新增或者修改      0新增   1修改   2审核

                        if(!dataMap.get("IfNew").toString().equals("0")){
                            dataMap.put("FPricing",lister.get(i).get("UnifiedPricing"));
                        }
                        dataMap.put("TPricing",map.get("UnifiedPricing"));//房源统一定价(变化后)
                        dataMap.put("OperId",dataMap.get("insby"));//当前操作人编号
                        dataMap.put("OperName",user.getName());//当前操作人名称
                        dataMap.put("OperTime",dataMap.get("instm"));//操作时间
                        seHousingInfoPricingMapper.addSeHousingInfoPricing(dataMap);
                    }
                    //    }
                }

            } catch (Exception e) {
                e.printStackTrace();
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }
        }
        finally {
            lock.unlock();
        }
        return result;
    }

}
